import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { SettingDrawer } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import { LogoutOutlined } from '@ant-design/icons';
import defaultSettings from '../config/defaultSettings';
import type { RequestConfig } from 'umi';
import type { Context, ResponseError } from 'umi-request';
import store from 'store';
import { HTTP_STATUS } from './constant';

// const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** request middleware */
const requestMiddleware = async (ctx: Context, next: () => void) => {
  const { req } = ctx;
  const { options } = req;
  const token: string | undefined = store.get('appToken');
  const { headers } = options;
  // 更新头部
  ctx.req.options.headers = {
    ...headers,
    Authorization: token ? token : '',
  };
  await next();
};

const responseInterceptor = async (response: Response) => {
  // 识别是否为分页
  return response;
};

const responseErrorHandler = (error: ResponseError) => {
  const { response } = error;
  if (response && response.status) {
    const errorText = HTTP_STATUS[response.status] || response.statusText;
    const { status, url } = response;
    console.error(`请求错误 ${status}: ${url} : ${errorText}`);
  }
  throw error;
};

export const request: RequestConfig = {
  errorConfig: {
    adaptor: (resData, ctx) => {
      // 若识别为列表请求，追加分页参数
      if (resData?.data?.length && resData?.meta?.pager) {
        resData.total = resData.meta.pager.total;
        resData.pageSize = ctx.req.options.params.pageSize;
        resData.current = ctx.req.options.params.current;
      }
      const data = {
        ...resData,
        success: resData.meta.code === 'SUCCESS',
        errorMessage: resData.meta.msg,
      };
      console.log(data, 'resData');
      return data;
    },
  },
  timeout: 60000,
  middlewares: [requestMiddleware],
  responseInterceptors: [responseInterceptor],
  responseErrorHandler,
};

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

const logout = () => {
  store.remove('appToken');
  history.push(loginPath);
};
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: [
      <a
        key="logout"
        onClick={() => {
          logout();
        }}
      >
        <LogoutOutlined />
        <span>登出</span>
      </a>,
    ],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
